<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Member extends Controller_Template {

    public $template = 'main';

    public function before() {
        parent::before();
        if (!Auth::instance()->logged_in() AND Request::current()->uri() !== 'login') {
            $this->request->redirect('/login');
        }
        if(Auth::instance()->logged_in('admin')) {
            $this->request->redirect('/admin');
        }
    }

    public function action_index() {
        $data['username'] = Auth::instance()->get_user()->username;
        $model = ORM::factory('project')->where("domain", "=", $data['username'])->find();
        $this->template->project_id = $model->project_id;
        $this->template->title = "Личный кабинет";
        $this->template->content = View::factory('cabinet', $data);
    }

    public function action_save() {
        $id_user = Auth::instance()->get_user()->id;
        $data['username'] = Auth::instance()->get_user()->username;
        $model = ORM::factory('project')->where("domain", "=", $data['username'])->find();
        $this->template->project_id = $model->project_id;
        $this->template->title = "Личный кабинет";
        $this->template->content = View::factory('cabinet', $data);
        if ($_POST) {
            $post = Validation::factory($_POST);
            $post->rule('email', 'not_empty')
                    ->rule('password', 'not_empty')
                    ->rule('email', 'email');
            if ($post->check()) {
                $model = ORM::factory('user', $id_user);
                $model->password = $_POST['password'];
                $model->email = $_POST['email'];
                if ($model->loaded()) {
                    $model->update();
                }
                $data['ok'] = "";
            } else {
                $data['errors'] = $post->errors('models/user');
                $this->template->project_id = $model->project_id;
                $this->template->title = "Личный кабинет";
                $this->template->content = View::factory('cabinet', $data);
            }
        }
    }

}

?>
